"use strict";
var React = require("react");
var AuthorForm = require("./authorForm");
var AuthorActions = require("../../actions/authorActions");
var AuthorStore = require("../../stores/authorStore");
var Router = require("react-router");
var toastr = require("toastr");

var ManageAuthorPage = React.createClass({
    mixins: [
        Router.Navigation
    ],

    statics: {
        willTransitionFrom: function (transition, component) {
            if (component.state.dirty && !confirm("leave without saving?")) {
                transition.abort();
            }
        }

    },

    getInitialState: function () {
        return {
            author: {id: '', firstName: '', lastName: ''},
            errors: {firstName: "", lastName: ""},
            dirty: false
        };
    },

    componentDidMount: function () {
    },

    componentWillMount: function () {
        var authorId = this.props.params.id;
        if (authorId) {
            this.setState({author: AuthorStore.getAuthorById(authorId)});
        }
    },

    setAuthorState: function (event) {
        this.state.dirty = true;

        var field = event.target.name;
        var value = event.target.value;
        this.state.author[field] = value;
        return this.setState({author: this.state.author});
    },

    authorFormIsValid: function () {
        var formIsValid = true;
        if (this.state.author.firstName.length < 3) {
            this.state.errors.firstName = "First name must be at least 3 characters.";
            formIsValid = false;
        }
        else {
            this.state.errors.firstName = "";
        }
        if (this.state.author.lastName.length < 3) {
            this.state.errors.lastName = "Last name must be at least 3 characters.";
            formIsValid = false;
        } else {
            this.state.errors.lastName = "";
        }


        if (!formIsValid) {
            this.setState({errors: this.state.errors});
        }

        return formIsValid;
    },

    saveAuthor: function (event) {

        event.preventDefault();
        if (!this.authorFormIsValid()) {
            return;
        }

        if(this.state.author.id){
            AuthorActions.updateAuthor(this.state.author);
        }else {
            AuthorActions.createAuthor(this.state.author);
        }
        this.state.dirty = false;

        toastr.success("Author saved.");
        this.transitionTo("authors");
    },

    render: function () {
        return (
            <div>
                <h1>Manage author page</h1>
                <AuthorForm author={this.state.author} errors={this.state.errors}
                            onChange={this.setAuthorState} onSave={this.saveAuthor}/>
            </div>

        );
    }
});

module.exports = ManageAuthorPage;
